#include "remove_ruler_pin.hpp"

#include "qbe/src/ecs/app.hpp"

#include "qbe/src/ecs/query.hpp"

#include "qbe/src/axis/axis.hpp"
#include "qbe/src/input/input.hpp"
#include "qbe/src/select/select.hpp"
#include "qbe/src/state/state.hpp"
#include "qbe/src/undoRedo/undoRedo.hpp"
#include "qbe/src/utils/utils.hpp"

#include "qbe/src/layout/layout.hpp"

#include "qbe/src/tools/auto_route_interface.h"
#include "qlib/all.h"

#include "qlib/geo/pin.h"
#include "qlib/geo/ruler.h"

namespace qbe::Remove_ruler_pin {

// 删除
void update(ecs::Query query, ecs::Bus& bus) {
  // 判断编辑模式为移动
  auto& state = query.get_resource<state::State>();

  if (state.getEditingMode() != state::EditingModeType::Remove_ruler_pin)
    return;

  // 获取cell和reg
  auto& cell = query.get_resource<qlib::Cell::s_ptr>();
  auto& reg = cell->reg;
  auto& layout_cmd = query.get_resource<layout::LayoutCmd>();

  // 获取输入 坐标系 撤销恢复
  auto& handModule = query.get_resource<vsg::ref_ptr<input::HandleBundle>>();
  auto& axisModule = query.get_resource<axis::Axis>();
  auto& undoRedoModule = query.get_resource<undoRedoT::UndoRedoModule>();
  auto& auto_route_interface_object = query.get_resource<qbe::tools::AutoRouteInterfaceObjcet>();

  // bool pressed_esc = qbe::getKeyPressed("edit", "dele obj", bus);

  undoRedoModule.start(cell);

  auto view_ruler = reg.view<qlib::Ruler::s_ptr>();
  view_ruler.each([&reg, &undoRedoModule, &layout_cmd](entt::entity e, qlib::Ruler::s_ptr ptr) {
    undoRedoModule.dele(e);
    layout_cmd.remove(e);
  });

  auto view_pin = reg.view<qlib::Pin::s_ptr>();
  view_pin.each([&reg, &undoRedoModule, &layout_cmd](entt::entity e, qlib::Pin::s_ptr ptr) {
    undoRedoModule.dele(e);
    layout_cmd.remove(e);
  });

  auto& sele_event_writer = query.get_event_writer<select::Event>();
  sele_event_writer.send({select::Code::SelectUpdate});
  sele_event_writer.send({select::Code::HoverUpdate});

  undoRedoModule.end();

  state.exit();
}

void Plugin::build(ecs::App& app) {
  app.add_stage<UpdateStage>();

  app.add_systems<UpdateStage>(update);
}

}  // namespace qbe::Remove_ruler_pin